#!/usr/bin/env python
#encoding: utf-8
import pygtk
pygtk.require('2.0')

import gtk
import gnomeapplet
import gobject
import sys
import logging
import thread, time
import urllib
import pycurl
import StringIO

# Based on invest-applet in gnome-applets
# from cloud services notifications

from dbus.mainloop.glib import DBusGMainLoop
import dbus
import time
# possible states, see http://projects.gnome.org/NetworkManager/developers/spec-08.html#type-NM_STATE
STATE_UNKNOWN		= dbus.UInt32(0)
STATE_ASLEEP		= dbus.UInt32(1)
STATE_CONNECTING	= dbus.UInt32(2)
STATE_CONNECTED		= dbus.UInt32(3)
STATE_DISCONNEDTED	= dbus.UInt32(4)

class NetworkManager:
	def GetState(self):
		self.state = STATE_UNKNOWN
		self.statechange_callback = None

		try:
			# get an event loop
			loop = DBusGMainLoop()

			# get the NetworkManager object from D-Bus
			bus = dbus.SystemBus(mainloop=loop)
			nmobj = bus.get_object('org.freedesktop.NetworkManager', '/org/freedesktop/NetworkManager')
			nm = dbus.Interface(nmobj, 'org.freedesktop.NetworkManager')

			# connect the signal handler to the bus
			bus.add_signal_receiver(self.handler, None,
					'org.freedesktop.NetworkManager',
					'org.freedesktop.NetworkManager',
					'/org/freedesktop/NetworkManager')

			# get the current status of the network manager
			self.state = nm.state()
			return self.state
		except Exception, msg:
			pass


	# the signal handler for signals from the network manager
	def handler(self,signal=None):
		if isinstance(signal, dict):
			state = signal.get('State')
			if state != None:
				self.state = state

				# notify about state change
				if self.statechange_callback != None:
					self.statechange_callback()

	def set_statechange_callback(self,handler):
		self.statechange_callback = handler



class tb_applet(gnomeapplet.Applet):
	title = 'Technobase.fm Applet' 
	version = '1.0'

	logging.basicConfig(level=logging.DEBUG)

	def __init__(self, applet, iid):
		logging.debug('__init__')
		

            	
		self.applet = applet
		
		self.create_menu()
		
		self.label = gtk.Label("Offline")

		self.applet.add(self.label)
		
		self.cb = gtk.Clipboard()
	
		#self.applet.connect('button-press-event',self.showMenu)
		self.applet.connect('change-background', self.change_background)
		
		self.nm = NetworkManager()
		# update every 60seconds
		self.seconds = 60
		gobject.timeout_add_seconds(self.seconds, self.update)
		self.update()
		self.applet.show_all()

		

	# when the theme background changes
	def change_background(self, applet, type, color, pixmap):
		logging.debug('change_background')
		applet.set_style(None)
		applet.modify_style(gtk.RcStyle())

		if type == gnomeapplet.COLOR_BACKGROUND:
		    applet.modify_bg(gtk.STATE_NORMAL, color)
		elif type == gnomeapplet.PIXMAP_BACKGROUND:
		    applet.get_style().bg_pixmap[gtk.STATE_NORMAL] = pixmap


	def create_menu(self):
		   xml="""<popup name="button3">
		<menuitem name="ItemCopy" 
			  verb="Copy" 
			  label="_Copy Track" 
			  pixtype="stock" 
			  pixname="gtk-copy"/>
		<menuitem name="ItemUpdate" 
			  verb="Update" 
			  label="_Update" 
			  pixtype="stock" 
			  pixname="gtk-refresh"/>
		<separator/>
		<menuitem name="ItemAbout" 
			  verb="About" 
			  label="_About" 
			  pixtype="stock" 
			  pixname="gtk-about"/>
		</popup>"""

		   verbs = [('About', self.show_about_dialog), ('Copy', self.cp_clipboard), ('Update', self.update)]
		   self.applet.setup_menu(xml, verbs, None)

		   
	#copy track in clipboard
	def cp_clipboard(self,*arguments):
		self.cb.set_text(self.label.get_text())

	#show about dialog
	def show_about_dialog(self,*arguments):
		dialog = gtk.AboutDialog()
		dialog.set_name("Technobase Gnome-Panel")
		dialog.set_version("1.0")
		dialog.set_copyright ("Copyright © 2009-2010 Luca Barbàra")
		dialog.set_comments("Get Technobase.fm Current Track")
		dialog.set_website ("http://code.google.com/p/weareone-gnome-panel/")
		dialog.set_authors (["Luca Barbàra"])
		dialog.run()
		dialog.hide()

	#update the current track
	def update(self,*arguments):
		if self.nm.GetState() == STATE_CONNECTED:
			self.label.set_text("We aRe One: " + get_track())
		else:
			self.label.set_text("Offline")
		return True
		
		
# function to run/register the class
def Start_applet(applet, iid):
	tb_applet(applet, iid)
	
	return gtk.TRUE

def get_track():
	b = StringIO.StringIO() 
	c = pycurl.Curl()
	c.setopt(c.URL, "http://www.technobase.fm")
	c.setopt(c.TIMEOUT,3)
	c.setopt(c.MAXREDIRS, 4)
	c.setopt(c.FOLLOWLOCATION,1)
	c.setopt(c.USERAGENT,"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1")
	c.setopt(c.REFERER,"http://www.google.com")
	c.setopt(c.HTTPHEADER, ["Expect:"])
	c.setopt(c.TIMEOUT, 0) 
	c.setopt(c.WRITEFUNCTION, b.write)
	c.perform()
	c.close()	
	source_html = b.getvalue()
	track = ""
	if source_html.find('style="color: #FFFFFF">') > 0:
		track = source_html[ source_html.find('style="color: #FFFFFF">')+23: source_html.find('<div style="width:40px;float:left;')-51]
	elif source_html.find('<div style="width:345px;float:left; margin-top:11px; overflow:hidden">') > 0:
		track = source_html[ source_html.find('<div style="width:345px;float:left; margin-top:11px; overflow:hidden">')+91: source_html.find('<div style="width:40px;float:left; margin-top:11px; overflow:hidden">')-27].strip()
	return track

if __name__ == '__main__':

   if len(sys.argv) > 1 and sys.argv[1] == '-d': # debugging
      mainWindow = gtk.Window()
      mainWindow.set_title('Applet window')
      mainWindow.connect('destroy', gtk.main_quit)
      applet = gnomeapplet.Applet()
      Start_applet(applet, None)
      applet.reparent(mainWindow)
      mainWindow.show_all()
      gtk.main()
      sys.exit()
   else:
	gnomeapplet.bonobo_factory("OAFIID:Gnome_Panel_TB_Factory", gnomeapplet.Applet.__gtype__, "Technobase.fm current Track", "1.0", Start_applet)
